﻿/* Waimea generate MSBuild from VS10 Solution
Copyright (C) 2011  Tim Dion

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

using System;
using System.Collections.Generic;
using System.Diagnostics;

using System.IO;
using Microsoft.Build.BuildEngine;

//todo fix installer
//todo print out solution details

namespace PunaForrest.VS10Waimea
{
    internal class ProjectNode : IDisposable
    {
        public string Filename { get; private set; }
        public Project MyProject { get; private set; }
        public List<ProjectNode> References { get; private set; }
        public List<ProjectNode> UpstreamFrom { get; private set; }
        public bool Collected { get; private set;  }

        private static Dictionary<string, ProjectNode> sNodes;
        private static Queue<ProjectNode> sQueue; 

        private List<string> mReferences;
        private bool mDisposed = false;

        static public void AddNode(string file)
        {
            var node = new ProjectNode(file);
            sNodes[file] = node; 

        }

        static ProjectNode()
        {
            sNodes = new Dictionary<string, ProjectNode>();
            sQueue = new Queue<ProjectNode>();
        }


        public void Dispose()
        {
            Dispose(true);      
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!mDisposed)
            {
                if (disposing)
                {
                    Filename = null;
                    MyProject = null;
                    References = null;
                    sNodes = null;
                    mReferences = null;
                    UpstreamFrom = null; 
                }
                mDisposed = true;
            }
        }
        public ProjectNode(string filename)
        {
            Filename = Path.GetFullPath(filename);
            MyProject = new Project();
            mReferences = new List<string>();
            References = new List<ProjectNode>();
            UpstreamFrom = new List<ProjectNode>();
            Collected = false; 

            try
            {
                MyProject.Load(filename);

                //Find Project ferences
                foreach (BuildItemGroup itemGroup in MyProject.ItemGroups)
                {
                    foreach (BuildItem item in itemGroup)
                    {
                        if (item.Name == "ProjectReference")
                        {
                            string path = Path.GetDirectoryName(filename);
                            path = Path.Combine(path, item.Include);
                            path = Path.GetFullPath(path);
                            if (File.Exists(path))
                            {
                                VS10WaimeaPackage.OutputCommandString("        ProjectReference:" + path); //full path
                                mReferences.Add(path);
                            }
                        }
                    }
                }
            }
            catch (InvalidProjectFileException exception)
            {
                Trace.WriteLine("ProjectNode:" + exception.Message);
            }
        }

        //Iterate throught projects and add references as subnodes. 
        public void BuildGraph()
        {
            //For each project, find its dependent and add them to the node. 
            foreach (string referenceProject in mReferences)
            {
                if (sNodes.ContainsKey(referenceProject))
                {
                    var referencedNode = sNodes[referenceProject];
                    References.Add(referencedNode);
                    referencedNode.UpstreamFrom.Add(this);  //children have to be built first
                }
      
            }
        }

        //Build all project references. 
        static public void BuildAllGraphs()
        {
            foreach (KeyValuePair<string, ProjectNode> node in sNodes)
            {
                node.Value.BuildGraph();
            }

        }

        static public void OutputAll(string solutionDirectory, string solutionFile, string userOptsFile)
        {

            string projFile = @"build.proj";     //todo use solution name? 
            string path = Path.Combine(solutionDirectory, projFile);
            VS10WaimeaPackage.OutputCommandString("writing MSBuild file to: " + path);

            StreamWriter writer = null; 

            try{
                writer = new StreamWriter(path);   
                writer.WriteLine("<!-- generated MS build Item. Reference this file from master build script. -->");
                writer.WriteLine(
                    " <Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">");

                writer.WriteLine("<ItemGroup>");

                while (sQueue.Count != 0)
                {
                    ProjectNode node = sQueue.Dequeue();
              
                    writer.Write("\t  <Projects Include=  \"");
                    //make project path relative to solution directory. 
                    Uri uri1 = new Uri(solutionDirectory);
                    Uri uri2 = new Uri(node.Filename);

                    Uri relativeUri = uri1.MakeRelativeUri(uri2);
                    writer.Write(relativeUri); 
                    writer.Write("\"/> \n");
                }

                writer.WriteLine("</ItemGroup>");
                writer.WriteLine("</Project>");
                writer.Flush();
            }
            catch(Exception ex)
            {
                VS10WaimeaPackage.OutputCommandString(ex.Message); //full path
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }

        static public void WalkAll()
        {
            foreach (KeyValuePair<string, ProjectNode> nodeKVP in sNodes)
            {
                if (nodeKVP.Value.Collected == false)
                {
                    nodeKVP.Value.WalkGraph(); 
                }
            }
        }

        public void WalkGraph()
        {
            //If I am upstream from nobody, than add me to the queue. Nobody depends on me. 
            if (UpstreamFrom.Count == 0)
            {
                sQueue.Enqueue(this);
                Collected = true;
                return;
            }
            //Add my references first. 
            foreach( ProjectNode node in References)
            {
                node.WalkGraph();
                if (node.Collected == false)
                {
                    sQueue.Enqueue(node);
                    node.Collected = true; 
                }
            }
        }

        //Note, this is not thread safe. 
        public void Reset()
        {
            foreach( KeyValuePair<string, ProjectNode> node in sNodes)
            {
                node.Value.Dispose();
            }

            sNodes = new Dictionary<string, ProjectNode>();
        }
    }
}